<?php
// +----------------------------------------------------------------------
// | ThinkPHP [ WE CAN DO IT JUST THINK ]
// +----------------------------------------------------------------------
// | Copyright (c) 2006~2017 http://thinkphp.cn All rights reserved.
// +----------------------------------------------------------------------
// | Licensed ( http://www.apache.org/licenses/LICENSE-2.0 )
// +----------------------------------------------------------------------
// | Author: 李邦琦 <1536549251@qq.com>
// +----------------------------------------------------------------------

namespace app\crm\model;
use think\Db;
use think\Model;
use think\Cache;
use think\Loader;

class Servicecustomer extends Model
{
    /**
     * 获取部门id下的所有子分类id
     * @param  string $dept_id 部门id
     * @return array           子分类id数组
     */
    public function getDepartment ($dept_id)
    {
        $dept_arr = array();
        $dept = Db::name('sys_department')->where('department_pid', $dept_id)->select();
        foreach ($dept as $val) {
            $dept_arr[] = $val['department_id'];
            $result[] = $this->getDepartment($val['department_id'], $dept_arr);
        }
        foreach ($result as $val) {
            if(is_array($val)) {
                $dept_arr = array_merge($dept_arr, $val);
            }
        }
        return $dept_arr;
    }


    /**
     * 获取客户资料列表
     * @param str $where <查询条件>
     * @param int $page <页码>
     * @param int $limit <每页显示条数>
     * @return array <日报列表信息>
     */
    public function getCustomerData($where,$page,$limit)
    {
        $menuname = "Service Customer";
        $p_menuname = $_SESSION['menu'][$menuname]; //父菜单
        $priv = $_SESSION["user_priv"][$p_menuname][$menuname]; 
        $username = $_SESSION["user_info"]["username"];

        $users = Cache::get('users');
        // $department = Cache::get('department');
        $count = Db::name('vip_customer_basic')->alias('b')->join('xy_vip_customer_detail d','b.customer_code = d.customer_code')->field('b.*, d.member_level, d.sex, d.age, d.last_order_time, d.last_call_time, d.integral, d.id_card, d.order_num, d.sign_num')->where($where)->count();
        // 查询状态为1的用户数据 并且每页显示10条数据
        $customerList = Db::name('vip_customer_basic')->alias('b')->join('xy_vip_customer_detail d','b.customer_code = d.customer_code')->field('b.*, d.member_level, d.sex, d.age, d.last_order_time, d.last_call_time, d.integral, d.id_card, d.order_num, d.sign_num')->where($where)->limit(($page-1)*$limit,$limit)->order('b.createtime DESC')->select();
        // print_r($customerList);exit;
        foreach ($customerList as &$val) {
            $val['create_name'] = $users[$val['create_user']]['cn_name'];
            $val['distribution'] = empty($val['distribution_time'])?'否':'是';
            switch ($val['sex']) {
                case '1': $val['sex'] = '男'; break;
                case '2': $val['sex'] = '女'; break;
            }
            switch ($val['member_level']) {
                case '1': $val['member_level'] = 'a类客户'; break;
                case '2': $val['member_level'] = 'b类客户'; break;
                case '3': $val['member_level'] = 'c类客户'; break;
                case '4': $val['member_level'] = 'd类客户'; break;
                case '5': $val['member_level'] = 'e类客户'; break;
            }
            switch ($val['customer_type']) {
                case 'first': $val['customer_type'] = '首单客户'; break;
                case 'second': $val['customer_type'] = '升级客户'; break;
                case 'vip': $val['customer_type'] = '会员客户'; break;

            }
            // print_r($_SESSION);exit;
            //判断号码是否加密
            if($priv["encrypt_phone"] == "Y"){
                if($username != "admin"){
                    $val["phone"] = substr($val["phone"],0,3)."*****".substr($val["phone"],-2);
                    $val["telephone"] = substr($val["telephone"],0,3)."*****".substr($val["telephone"],-2);
                }
            }
        }
        $rowsList = count($customerList) ? $customerList : false;
        $arrData["code"] = 0;
        $arrData["msg"] = '';
        $arrData["count"] = $count;
        $arrData["data"] = $rowsList;
        return $arrData;
    }


    public function getGroups ()
    {
        $createname = $_SESSION['user_info']['username'];
        $page = $_REQUEST["page"];
        $limit = $_REQUEST["limit"];
        $users = Cache::get('users');
        $count = Db::name('vip_group')->where('createname="'.$createname.'"')->count();
        // 查询状态为1的用户数据 并且每页显示5条数据
        $groupData = Db::name('vip_group')->where('createname="'.$createname.'"')->limit(($page-1)*$limit,$limit)->order('id DESC')->select();

        $rowsList = count($groupData) ? $groupData : false;
        $arrData["code"] = 0;
        $arrData["msg"] = '';
        $arrData["count"] = $count;
        $arrData["data"] = $rowsList;
        // print_r($arrData);exit;
        return $arrData;
    }


    /**
     * 新增分组
     * @param  array $data 新增数据
     * @return json        新增结果
     */
    public function insertGroup ($data)
    {
        $result = Db::name('vip_group')->insert($data);
        if ($result){
            echo json_encode(array('success'=>true,'msg'=>'保存成功！'));
        } else {
            echo json_encode(array('msg'=>'保存失败！'));
        }
    }


    /**
     * 更新分组
     * @param  array $data 更新数据
     * @return json        更新结果
     */
    public function updateGroup ($data)
    {
        $result = Db::name('vip_group')->update($data);
        if ($result){
            echo json_encode(array('success'=>true,'msg'=>'编辑成功！'));
        } else {
            echo json_encode(array('msg'=>'编辑失败！'));
        }
    }


    /**
     * 删除分组
     * @param  string $ids 要被删除的id
     * @return json        删除状态
     */
    public function delGroup ($ids)
    {
        $result = Db::name('vip_group')->where('id IN ('.$ids.')')->delete();
        if ($result){
            Db::name('vip_customer_basic')->where('groups IN ('.$ids.')')->setField('groups', null);
            echo json_encode(array('success'=>true,'msg'=>'删除成功！'));
        } else {
            echo json_encode(array('msg'=>'删除失败！'));
        }
    }


    /**
     * 获取基本资料和收货地址
     * @param  string $customer_code 获取条件
     * @return json                  地区数据
     */
    public function getAddOrder ($customer_code)
    {
        $result = Db::name('vip_customer_basic')->alias('b')->join('xy_vip_customer_address a','b.customer_code = a.customer_code')->field('b.*,a.*')->where('a.customer_code', $customer_code)->find();
        return $result;
    }


    /**
     * 分配客户资料
     * @param  array  $customer_codes   被分配的资料id
     * @param  string $create_user      被分配到的用户
     * @return json                     执行状态
     */
    public function transferCustomer($where, $create_user, $transfer_note)
    {
        $users = Cache::get('users');
        // print_r($users);exit;
        $data = array(
            'create_user' => $create_user,
            'transfer_note' => $transfer_note,
            'distribution_time' => date('Y-m-d H:i:s'),
            'task_id' => null,
            'recovery' => 1,
        );

        $result = Db::name('vip_customer_basic')->where($where)->update($data);
        return $result;
    }


    /**
     * 更新客户基本资料
     * @param  array $data 需要更新的数据
     * @return bool        更新状态 true/false
     */
    public function updateBasicCustomer ($data)
    {
        $result = Db::name('vip_customer_basic')->where('customer_code', $data['customer_code'])->update($data);
        if ($result){
            return true;
        } else {
            return false;
        }
    }


    /**
     * 更新客户基本资料
     * @param  array $data 需要更新的数据
     * @return bool        更新状态 true/false
     */
    public function updateDetailCustomer ($data)
    {
        $result = Db::name('vip_customer_detail')->where('customer_code', $data['customer_code'])->update($data);
        if ($result){
            return true;
        } else {
            return false;
        }
    }


    /**
     * 更新收货地址
     * @param  array $data 需要更新的数据
     * @return bool        更新状态 true/false
     */
    public function updateAddressCustomer ($data)
    {
        // 先查是否存在该客户的收货地址
        // 有 update 无 insert
        $res = Db::name('vip_customer_address')->where('customer_code', $data['customer_code'])->find();
        if ($res) {
            $result = Db::name('vip_customer_address')->where('customer_code', $data['customer_code'])->update($data);
        } else {
            $result = Db::name('vip_customer_address')->where('customer_code', $data['customer_code'])->insert($data);
        }
        // 返回更新结果
        if ($result){
            return true;
        } else {
            return false;
        }
    }


    /**
     * 获取收货地址
     * @param  string $customer_code 获取条件
     * @return json                  地区数据
     */
    public function getAddress ($customer_code)
    {
        $result = Db::name('vip_customer_address')->where('customer_code', $customer_code)->find();
        return $result;
    }


    /**
     * 获取地区
     * @param  string $parent_id 地区父级id
     * @return array             地区数组
     */
    public function getEditAddress ($parent_id) 
    {
        $result = Db::name('sys_address')->where('parent_id='.$parent_id)->select();
        return $result;
    }


    /**
     * 获取病情列表
     * @param  string $where 获取条件
     * @return array         获取到的数据
     */
    public function getIllness ($where)
    {
        $page = $_REQUEST["page"];
        $limit = $_REQUEST["limit"];
        $users = Cache::get('users');
        $count = Db::name('vip_illness')->where($where)->count();
        // 查询状态为1的用户数据 并且每页显示5条数据
        $illnessData = Db::name('vip_illness')->where($where)->limit(($page-1)*$limit,$limit)->order('create_time DESC')->select();
        $illnessSelect = Cache::get('illnessSelect');
        foreach ($illnessData as &$val) {
            $val['create_name'] = $users[$val['create_user']]['cn_name'];
            $val['illness_type'] = $illnessSelect[$val['illness_type']]['illness_type'];
        }
        $rowsList = count($illnessData) ? $illnessData : false;
        $arrData["code"] = 0;
        $arrData["msg"] = '';
        $arrData["count"] = $count;
        $arrData["data"] = $rowsList;
        // print_r($arrData);exit;
        return $arrData;
    }


    /**
     * 获取回访记录列表
     * @param  string $where 获取条件
     * @return array         获取到的数据
     */
    public function getVisit ($where)
    {
        $menuname = "Customere List";
        $p_menuname = $_SESSION['menu'][$menuname]; //父菜单
        $priv = $_SESSION["user_priv"][$p_menuname][$menuname]; 
        $username = $_SESSION["user_info"]["username"];

        $page = $_REQUEST["page"];
        $limit = $_REQUEST["limit"];
        $users = Cache::get('users');
        $visit = Cache::get('visit');
        $count = Db::name('vip_visit_record')->where($where)->count();
        // 查询状态为1的用户数据 并且每页显示5条数据
        $visitData = Db::name('vip_visit_record')->where($where)->limit(($page-1)*$limit,$limit)->order('create_time DESC')->select();
        foreach ($visitData as &$val) {
            $val['create_name'] = $users[$val['create_user']]['cn_name'];
            //判断号码是否加密
            if($priv["encrypt_phone"] == "Y"){
                if($username != "admin"){
                    $val["phone"] = substr($val["phone"],0,3)."*****".substr($val["phone"],-2);
                }
            }
            $val['visit_type_id'] = $visit['visit_type'][$val['visit_type_id']]['visit_type'];
            $val['visit_result_id'] = $visit['visit_result'][$val['visit_result_id']]['result_name'];
            $val['task_id'] = empty($val['task_id'])?'无':$val['task_id'];
        }
        $rowsList = count($visitData) ? $visitData : false;
        $arrData["code"] = 0;
        $arrData["msg"] = '';
        $arrData["count"] = $count;
        $arrData["data"] = $rowsList;
        // print_r($arrData);exit;
        return $arrData;
    }


    /**
     * 新增病情
     * @param  array $data 新增数据
     * @return json        新增状态
     */
    public function insertIllness ($data)
    {
        $result = Db::name('vip_illness')->insert($data);
        if ($result){
            echo json_encode(array('success'=>true,'msg'=>'保存成功！'));
        } else {
            echo json_encode(array('msg'=>'保存失败！'));
        }
    }


    /**
     * 获取单条病情
     * @param  string $id 病情id
     * @return array      病情情况
     */
    public function getIllnessInfo($id)
    {
        $where = "id=$id";
        $result = Db::name('vip_illness')->where($where)->find();
        return $result;
    }


    /**
     * 编辑病情
     * @param  array $data 需要更新的数据
     * @return json        更新状态
     */
    public function updateIllness($data)
    {
        $where = "id=".$data['id'];
        $result = Db::name('vip_illness')->where($where)->update($data);
        if ($result){
            echo json_encode(array('success'=>true,'msg'=>'编辑成功！'));
        } else {
            echo json_encode(array('msg'=>'编辑失败！'));
        }
    }


    /**
     * 删除病情
     * @param  string $where 删除条件
     * @return json          删除状态
     */
    public function delIllness ($where) 
    {
        if (empty($where)) return false;
        $result = Db::name('vip_illness')->where($where)->delete();
        if ($result){
            echo json_encode(array('success'=>true,'msg'=>'删除成功！'));
        } else {
            echo json_encode(array('msg'=>'删除失败！'));
        }
    }


    /**
     * 新增回访记录
     * @param  array $data 新增数据
     * @return json        新增状态
     */
    public function insertVisit ($data)
    {
        // 先根据客户资料id查到客户电话和任务id
        $res = Db::name('vip_customer_basic')->field('phone')->where("customer_code='".$data['customer_code']."'")->find();
        $data['visit_phone'] = $res['phone'];
        // 新增
        $result = Db::name('vip_visit_record')->insert($data);
        if ($result){
            // 添加成功 更新最后回访时间
            $cus = Db::name('vip_customer_detail')->where("customer_code = '".$data['customer_code']."'")->update(['last_call_time' => date("Y-m-d H:i:s")]);
            echo json_encode(array('success'=>true,'msg'=>'保存成功！'));
        } else {
            echo json_encode(array('msg'=>'保存失败！'));
        }
    }


    /**
     * 删除病情
     * @param  string $where 删除条件
     * @return json          删除状态
     */
    public function delVisit ($where) 
    {
        if (empty($where)) return false;
        $result = Db::name('vip_visit_record')->where($where)->delete();
        if ($result){
            echo json_encode(array('success'=>true,'msg'=>'删除成功！'));
        } else {
            echo json_encode(array('msg'=>'删除失败！'));
        }
    }


    /**
     * 获取单条回访记录
     * @param  string $id 主键
     * @return array      获取到的数据
     */
    public function getVisitInfo ($id)
    {
        $where = "id=$id";
        $result = Db::name('vip_visit_record')->where($where)->find();
        return $result;
    }


    /**
     * 更新回访记录
     * @param  array $data 更新数据
     * @return json        更新状态
     */
    public function updateVisit($data)
    {
        $where = "id=".$data['id'];
        // print_r($where);exit;
        $result = Db::name('vip_visit_record')->where($where)->update($data);
        if ($result){
            echo json_encode(array('success'=>true,'msg'=>'编辑成功！'));
        } else {
            echo json_encode(array('msg'=>'编辑失败！'));
        }
    }


    /**
     * 获取分组列表
     * @return array 分组信息
     */
    public function getGroupsOption () 
    {
        $groupData = Db::name('vip_group')->where('createname="'.$_SESSION['user_info']['username'].'"')->order('id DESC')->select();
        return $groupData;
    }

}